//
//  PickerSelector.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/1.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation

import Eelay

public class PikerSelector: TypeInitController{
    

    public required init() {
        super.init()
        self.modalPresentationStyle = .overFullScreen
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public var picker:BasePiker = BasePiker()
    
    
    private var bottom_constrain = NSLayoutConstraint()
    
    
    private var show_statu_c:CGFloat = 0
    private var hiden_statu_c:CGFloat = Swidth*0.6 + 40
    
    var contentV:UIView = UIView()
    let backV = UIView()
    
    public override func viewDidLoad() {
        
        super.viewDidLoad()
        
        
        let canleBt = UIButton()
        let confimBt = UIButton()
        let bar = UIView()
        
        view.backgroundColor = .clear
        
        let sty = UIBlurEffect.Style.extraLight
        let blurEffect = UIBlurEffect(style: sty)
        let blurView = UIVisualEffectView(effect: blurEffect)


        
        view.eelay = [
            [backV,[ee.T.L.B.R]],
            [contentV,[ee.L.R]],
        ]
        backV.alpha = 0
        
        backV.backgroundColor = UIColor(shex:"#0002")
        
        
        self.bottom_constrain = NSLayoutConstraint(item: contentV, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: self.hiden_statu_c)
        view.addConstraint(bottom_constrain)
        
        
        let h = Swidth*0.6
        
        contentV.eelay = [
            [blurView,[ee.T.L.B.R]],
            [bar,[picker.picker,ee.T,ee.B],[ee.L.R],"40",[ee.T]],
            [picker.picker,[ee.L.B.R],"\(h)"],
        ]
        
        bar.eelay = [
            [canleBt,[ee.Y],[ee.L,10]],
            [confimBt,[ee.Y],[ee.R,-10]]
        ]
        
        
        canleBt.ui.ntitle(title: "取消".loc).ncolor(hex: "#333")
        confimBt.ui.ntitle(title: "确定".loc).ncolor(hex: "#333")
        confimBt.addTarget(self, action: #selector(confirm), for: .touchUpInside)
        canleBt.addTarget(self, action: #selector(hiden), for: .touchUpInside)
        
    }
    
    @objc func confirm() {
        if picker.confirm()
        {
            hiden()
        }
    }
    
    override public func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        show()
    }
    
    override public func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    
    
    public func show() {
        self.bottom_constrain.constant = 0.0
        weak var wself = self
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.25)
        UIView.setAnimationCurve(UIView.AnimationCurve.init(rawValue: 7)!)
        backV.alpha = 1.0
        wself?.bottom_constrain.constant = wself?.show_statu_c ?? 0
        wself?.view.setNeedsLayout()
        wself?.view.layoutIfNeeded()
        wself?.contentV.setNeedsLayout()
        wself?.contentV.layoutIfNeeded()
        UIView.commitAnimations()
    }
    
    @objc public func hiden() {
        weak var wself = self
        
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.25)
        UIView.setAnimationCurve(UIView.AnimationCurve.init(rawValue: 7)!)
        wself?.bottom_constrain.constant = wself?.hiden_statu_c ?? 0
        wself?.view.setNeedsLayout()
        wself?.view.layoutIfNeeded()
        wself?.contentV.setNeedsLayout()
        wself?.contentV.layoutIfNeeded()
        backV.alpha = 0
        UIView.commitAnimations()
        co_delay(delay: 0.25) {
            wself?.dismiss(animated: false, completion: {
                
            })
        }
    }
    
    
     public func canel() {
        self.hiden()
    }
    
}

private let unselectStr = "未选择".loc

//private func typesMake(name:String,count:Int=10) -> [String] {
//    var names:[String] = [String]()
//    names.append("\(unselectStr)")
//    for i in 0...count
//    {
//        names.append("\(i)\(name)")
//    }
//    return names
//
//}

open class BasePiker:NSObject {
    public var picker: UIView = UIPickerView()
    
    open func show(at:UIViewController) {
        
        let ctr = PikerSelector()
        
        ctr.picker = self
        
        at.present(ctr, animated: false) {
            
        }
    }
    
    open func confirm()->Bool {
        
        return true
    }
    
}


extension NSMutableArray{
    fileprivate func provinceIndex(with id:String?) -> Int {
        return index(with: id, lever: .province)
    }
    
    fileprivate func cityIndex(with id:String?) -> Int {
        return index(with: id, lever: .city)
    }
    
    fileprivate func areaIndex(with id:String?) -> Int {
        return index(with: id, lever: .area)
    }
    
    
    fileprivate func index(with id:String?,lever:PlaceNode)->Int{
        
        let idStr = id ?? "OO"
        var index = 0
        for(i,one) in self.enumerated()
        {
            if let dict = one as? NSMutableDictionary
            {
                if dict[lever.valueKey,"XXX"] == idStr{
                    index = i
                    break
                }
            }
            continue
        }
        return index
    }
    
    fileprivate var porvince_0_ID:String{
        return self["0.\(PlaceNode.province.valueKey)",""]
    }
    
    fileprivate var porvince_1_ID:String{
        return self["1.\(PlaceNode.province.valueKey)",""]
    }
    
    fileprivate var city_0_ID:String{
        let value = self["0.\(PlaceNode.city.valueKey)",""]
        
        return value
    }
    
    fileprivate var city_1_ID:String{
        return self["1.\(PlaceNode.city.valueKey)",""]
    }
    fileprivate var area_0_ID:String{
        return self["0.\(PlaceNode.area.valueKey)",""]
    }
    
    fileprivate var area_1_ID:String{
        return self["1.\(PlaceNode.area.valueKey)",""]
    }    
}


public class AddressPiker:BasePiker,UIPickerViewDelegate,UIPickerViewDataSource {
    
    public var provinces = PlaceNode.province.filter().mutable_array
    public var citys = PlaceNode.city.filter("XX").mutable_array
    public var areas = PlaceNode.area.filter("XX").mutable_array
    
    
    public var selectAction:((province:String?,city:String?,area:String?),([String:Any]),String)->Void = {_,_,_ in}
    
    public func initData() {

        citys = PlaceNode.city.filter(provinces.porvince_0_ID).mutable_array
        areas = PlaceNode.area.filter(citys.city_0_ID).mutable_array

        self.values = (provinces.porvince_0_ID,citys.city_0_ID,areas.area_0_ID)
//        __picker.reloadAllComponents()
    }
    
    public var commingValues:(province:String?,city:String?,area:String?){
        set{
            guard let p = newValue.province,let c = newValue.city,let a = newValue.area else {
                return
            }
            self.values = (p,c,a)
        }
        get{
            return values
        }
    }

    public var values:(province:String?,city:String?,area:String?) = (nil,nil,nil)
    {
    
        didSet{
            if let p = values.province
            {
                __picker.selectRow(provinces.provinceIndex(with: p), inComponent: 0, animated: false)

                
                self.citys = PlaceNode.city.filter(p).mutable_array
                __picker.reloadComponent(1)
                __picker.selectRow(citys.cityIndex(with: values.city), inComponent: 1, animated: false)
                
                 areas = PlaceNode.area.filter(citys.city_0_ID).mutable_array
                __picker.reloadComponent(2)
                __picker.selectRow(areas.areaIndex(with: values.area), inComponent: 2, animated: false)
            }
        
            if let c = values.city
            {
                self.areas = PlaceNode.area.filter(c).mutable_array
                __picker.reloadComponent(2)
                __picker.selectRow(citys.cityIndex(with: c), inComponent: 2, animated: false)
            }
            if let a = values.area
            {
                __picker.selectRow(areas.areaIndex(with: a), inComponent: 2, animated: false)
            }
        }
    }
    
    
    public override func confirm() -> Bool {
        
        var info = [String:Any]()
        var names = [String]()
        if let p = PlaceNode.province.get(values.province){

            info["province"] = p
            names.append(p.mutable_dictionary["name","省"])
        }
        if let c = PlaceNode.city.get(values.city)
        {
            info["city"] = c
            names.append(c.mutable_dictionary["name","市"])

        }
        if let a = PlaceNode.area.get(values.area)
        {
            info["area"] = a
            names.append(a.mutable_dictionary["name","区"])
        }
        self.selectAction(values,info,names.joined(separator: " "))
        return true
    }
    
    public func row(value:String?,list:NSMutableArray) -> Int? {
        var index:Int?
        if let v = value
        {
            list.list { (dict:NSMutableDictionary, i) in
                if dict["id","XXX"] == v
                {
                    index = i
                }
            }
        }
        return index
        
    }
    
    var __picker:UIPickerView{
        get{
            return (picker as? UIPickerView) ?? UIPickerView()
        }
    }
    
    
    public override required init() {
        super.init()
        __picker.delegate = self
        __picker.dataSource = self
        self.initData()
    }
    
    public func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
    
    
    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 0:
            return provinces.count
        case 1:
            return citys.count
        case 2:
            return areas.count
        default:
            return 0
        }
    }
    
    public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        var province = values.province
        var city = values.city
        var area = values.area
        switch component {
        case 0:
            province = self.provinces["\(row).\(PlaceNode.province.valueKey)",""]
            citys = PlaceNode.city.filter(province!).mutable_array
            city = citys.city_0_ID

            areas = PlaceNode.area.filter(citys.city_0_ID).mutable_array
            area = areas.area_0_ID

        case 1:
            city = self.citys["\(row).\(PlaceNode.city.valueKey)",""]
            areas = PlaceNode.area.filter(city!).mutable_array
            area = areas.area_0_ID
        case 2:
//            print("=====kkkjjjjs|\(self.areas)")
            area = self.areas["\(row).\(PlaceNode.area.valueKey)",""]
        default:
            break
        }
        
        
        self.values = (province,city,area)
        

    }
    
    
    public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        var str = ""
        switch component {
        case 0:
            str = provinces["\(row).name",""]
        case 1:
            str = citys["\(row).name",""]
        case 2:
            str = areas["\(row).name",""]
        default:
            str = ""
        }
        
        let lable = UILabel()
        
        
        _ = lable.ui.font18.cl_333.center.text(str)
        if str == unselectStr
        {
            _ = lable.ui.cl_999.font16
        }
        return lable
        
    }
    
}
